var path = require('path');
var webpack = require("webpack");
// var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CompressionWebpackPlugin = require('compression-webpack-plugin');
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

var HtmlWebpackPlugin = require('html-webpack-plugin');

var chalk = require('chalk');
var shell = require('shelljs');

var dir_root = path.resolve(__dirname); // 项目目录
var dir_web = path.join(dir_root, "src");   // 开发目录

var dir_resource_css = path.join(dir_root, "dist/css"); // 生成css的目录
var dir_resource_js = path.join(dir_root, "dist/js");   // 生成js的目录
var dir_resource_img = path.join(dir_root, "dist/images");   // 生成img的目录




process.env.NODE_ENV = 'production';

var webpackConfig = {
    entry: {
        app: "./src/main.js"// 单入口
    },
    output: {
        path: path.resolve(__dirname, ''),// 绝对路径，一般指定项目总目录为输出目录，然后对输出的文件进行自定义
        filename: "dist/js/[name].[chunkhash:6].js", // 每个输出 bundle 的名称
        publicPath: "/", // 对于按需加载(on-demand-load)或加载外部资源(external resources)（如图片、文件等）
        chunkFilename: "dist/js/[name].[chunkhash:6].js",// 按需加载(on-demand loaded)的 chunk 文件的名称
        jsonpFunction: 'WP',// 用于按需加载(load on-demand) chunk 的 JSONP 函数
    },
    module: {
        rules: [

            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        scss: 'vue-style-loader!css-loader?minimize=true!sass-loader', // <style lang="scss">
                        sass: 'vue-style-loader!css-loader?minimize=true!sass-loader' // <style lang="sass">
                    }
                }
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            minimize: true // 将css压缩
                        }
                    },
                    {
                        loader: 'sass-loader'
                    }
                ]
            },
            {
                test: /\.js$/,
                include: /src/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            // url-loader 需要file-loader，当文件超过limit指定的大小是，会自动使用file-loader
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 8192, // 8kb(8*1024)
                    name: 'dist/images/[name].[hash:7].[ext]'
                }
            },
            // {
            //     test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            //     loader: 'url-loader',
            //     query: {
            //         limit: 10000,
            //         name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
            //     }
            // }


        ]
    },

    plugins: [

        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,// 删除警告
                drop_console: true,// 删除console
            },
            output: {
                // ascii_only:true,// 汉字转ascii，开启此项后打包文件将会变大（中文转换的那部分大小）
                comments: false,
            },
            // sourceMap: false
        }),

        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: function (module) {
               // 该配置假定你引入的 vendor 存在于 node_modules 目录中
               return module.context && module.context.indexOf( path.join(__dirname, 'node_modules') ) !== -1;
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest',
            chunks: ['vendor']
        }),
        new HtmlWebpackPlugin({
            filename: path.resolve(__dirname, 'index.html'),
            template: path.resolve(__dirname, 'src/template.html'),
            inject: true,
            chunksSortMode: 'dependency'
        }),
        // 开启 gzip 压缩
        // new CompressionWebpackPlugin({
        //     asset: '[path].gz[query]',
        //     algorithm: 'gzip',
        //     test: /\.js$|\.css$/, // 压缩 js 与 css
        //     threshold: 10240,
        //     minRatio: 0.8
        // })


        // 分析包体依赖
        // new BundleAnalyzerPlugin({
        //     analyzerPort: 8989,
        // }),

    ]

}



// 不建议对线上的图片资源进行删除操作
shell.rm('-rf', dir_resource_css);
shell.rm('-rf', dir_resource_js);
// shell.mkdir('-p', path.join(dir_root, "dist"));
// shell.config.silent = true;
// shell.cp('-R', path.join(dir_web, "images"), dir_resource_img);
// shell.config.silent = false;

webpack(webpackConfig, function (err, stats) {
    if (err) throw err
    process.stdout.write(stats.toString({
        colors: true,
        modules: true,
        children: false,
        chunks: false,
        chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
})

